package org.dromara.timemate.service.impl;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.timemate.domain.WearerUser;
import org.dromara.timemate.domain.bo.WearerUserBo;
import org.dromara.timemate.domain.vo.WearerUserVo;
import org.dromara.timemate.mapper.WearerUserMapper;
import org.dromara.timemate.service.WearerUserService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import jakarta.annotation.Resource;

/**
 * 穿戴用户Service业务层处理
 *
 * @author Lion Li
 * @date 2021-07-26
 */
@Service
public class WearerUserServiceImpl implements WearerUserService {

    @Resource
    private WearerUserMapper baseMapper;

    @Override
    public TableDataInfo<WearerUserVo> queryPageWearerUserList(PageQuery pageQuery) {

        // 获取 user_id
        Long userId = LoginHelper.getUserId();
        LambdaQueryWrapper<WearerUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(userId != null, WearerUser::getUserId, userId);
        Page<WearerUser> page = baseMapper.selectPage(pageQuery.build(), lqw);
        List<WearerUser> records = page.getRecords();

        // jdk 8 + lambda 表达式
        List<WearerUserVo> retList = records.stream().map(new Function<WearerUser, WearerUserVo>() {

            @Override
            public WearerUserVo apply(WearerUser wearerUser) {
                WearerUserVo vo = new WearerUserVo();
                vo.setId(wearerUser.getId());
                vo.setUserId(wearerUser.getUserId());
                vo.setWearerName(wearerUser.getWearerName());
                vo.setGender(wearerUser.getGender());
                return vo;
            }
        }).collect(Collectors.toList());
        Page<WearerUserVo> retPage = new Page<>();
        retPage.setRecords(retList);
        retPage.setTotal(page.getTotal());
        retPage.setCurrent(page.getCurrent());
        retPage.setSize(page.getSize());
        return TableDataInfo.build(retPage);

    }

    @Override
    public Boolean addWearerUser(WearerUserBo wearerUserBo) {
        String tenantId = LoginHelper.getTenantId();
        Long UserId = LoginHelper.getUserId();
        WearerUser wearerUser = new WearerUser();
        wearerUser.setUserId(UserId);
        wearerUser.setWearerName(wearerUserBo.getWearerName());
        wearerUser.setGender(wearerUserBo.getGender());
        wearerUser.setTenantId(tenantId);
        if (baseMapper.insert(wearerUser) > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean deleteWearerUserByIds(List<Long> id) {
        return baseMapper.deleteBatchIds(id) > 0;
    }

}
